package com.request.service.impl.shop.jh;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.JHErrorCodeEnum;
import com.request.common.utils.HttpUtils;
import com.request.entity.PhoneOrderWaitCheck;
import com.request.service.QueryOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:
 * Create DateTime: 2020-04-22 17:25
 *
 * 

 */
@Slf4j
@Service
public class JHQueryOrderProcessor implements QueryOrderProcessor {

    private static Map<String, String> HEADER_MAP = new HashMap<>(2);

    static {
        HEADER_MAP.put("Content-Type","application/json;charset=utf-8");
    }

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Override
    public void sendRequest(PhoneOrderWaitCheck orderWaitCheck) {
        handlerOrderExecutor.execute(() -> executeWaitOrderQuery(orderWaitCheck));
    }

    /**
     * 执行待查询订单查询
     *
     * @param phoneOrderWaitCheck 待查询订单
     */
    private void executeWaitOrderQuery(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        Map<String, Object> params = new HashMap<>(2);
        String result = null;
        try {
            String querySite = phoneOrderWaitCheck.getQuerySite();
            String platformOrderNo = phoneOrderWaitCheck.getPlatformOrderNo();

            params.put("userOrderNumber", platformOrderNo);
            params.put("interfaceSecretKey", phoneOrderWaitCheck.getAppKey());

            result = sendRequestForWaitOrder(querySite, params);
            JSONObject jsonResult = JSON.parseObject(result);
            Integer ret = jsonResult.getInteger("ret");
            String detailMessage = jsonResult.getString("msg");
            if (JHErrorCodeEnum.getByValue(ret) != null) {
                throw new RuntimeException("响应ret为：" + ret);
            } else {
                String jsonCardList = jsonResult.getString("cardList");
                JSONObject jsonObject = JSONObject.parseObject(jsonCardList);

                Integer status = jsonObject.getInteger("status");
                String demandNumber = jsonObject.getString("demandNumber");

                phoneOrderWaitCheck.setShopOrderNo(demandNumber);
                phoneOrderWaitCheck.setStatus(status);
                phoneOrderWaitCheck.setMessage(detailMessage);

                saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
            }
        } catch (Exception e) {
            saveWaitOrderQueryForFailed(phoneOrderWaitCheck);
            log.error("【JH】【超时检查】请求商户出现异常，待检查订单信息为：{}, 参数为：{}, 响应结果为:{}, 详情为：{}",
                    phoneOrderWaitCheck, params.toString(), result, e);
        }

    }

    /**
     * 发送Http请求
     *
     * @param url    请求路径
     * @param params 参数
     * @return 响应结果
     */
    private String sendRequestForWaitOrder(String url, Map<String, Object> params) {
        return HttpUtils.doPost(url, params, HEADER_MAP);
    }

    /**
     * 放入成功队列
     */
    private void saveWaitOrderQueryForSuccess(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_SUCCESS, JSON.toJSONString(phoneOrderWaitCheck));
    }

    /**
     * 放入失败队列
     */
    private void saveWaitOrderQueryForFailed(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_FAILED, JSON.toJSONString(phoneOrderWaitCheck));
    }
}
